package com.ktg.mes.erpBom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.mes.erpBom.entity.T6ErpProductStructureItem;
import com.ktg.mes.erpBom.mapper.T6ErpProductStructureItemMapper;
import com.ktg.mes.erpBom.service.IT6ErpProductStructureItemService;
import com.ktg.mes.erpInventory.entity.T6ErpInventory;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.domain.MdProductBom;
import com.ktg.mes.md.service.IMdItemService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//@DS("erp-datasource")
@Service
public class T6ErpProductStructureItemServiceImpl extends ServiceImpl<T6ErpProductStructureItemMapper, T6ErpProductStructureItem> implements IT6ErpProductStructureItemService {

    @Autowired
    private IMdItemService iMdItemService;


    @Override
    public List<MdProductBom> queryListByLastPubufts(@Param("pubufts") String pubufts){
        List<T6ErpProductStructureItem> srcList = this.baseMapper.queryListByLastPubufts(pubufts);
        ArrayList distList = new ArrayList<>();
        for (T6ErpProductStructureItem item:srcList) {
            MdProductBom productBom = toMdProductBom(item);
            if (productBom != null){
                distList.add(productBom);
            }
        }
        return distList;
    }

    public MdProductBom toMdProductBom(T6ErpProductStructureItem srcItem) {
        MdProductBom dist = new MdProductBom();
        dist.setPubufts(Long.valueOf(srcItem.getToPubufts()));
        dist.setAutoId(srcItem.getAutoID());
        dist.setCreateTime(new Date());
        dist.setUpdateTime(new Date());
        MdItem mainItem = iMdItemService.selectMdItemByCode(srcItem.getCPSPCode());
        if (mainItem != null) {
            dist.setItemId(mainItem.getItemId());
            dist.setItemOrProduct(mainItem.getItemCode());
        }
        MdItem subItem = iMdItemService.selectMdItemByCode(srcItem.getCPSCode());
        if (subItem != null) {
            dist.setBomItemId(subItem.getItemId());
            dist.setBomItemCode(subItem.getItemCode());
            dist.setBomItemName(subItem.getItemName());
            dist.setBomItemSpec(subItem.getSpecification());
            dist.setUnitOfMeasure(subItem.getUnitOfMeasure());
        }
        return dist;
    }
}
